package com.huiminpay.merchant.service;

import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.exception.BusinessCast;
import com.huiminpay.common.cache.exception.BusinessException;
import com.huiminpay.common.cache.util.PhoneUtil;
import com.huiminpay.common.cache.util.QiniuUtils;
import com.huiminpay.merchant.convert.MerchantRegisterConvert;
import com.huiminpay.merchant.vo.MerchantDetailVO;
import com.huiminpay.merchant.vo.MerchantRegisterVo;
import com.yh.merchant.api.MerchantServiceApi;
import com.yh.merchant.dto.MerchantDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: HWW
 * @Date: 2021/8/1817:41
 * @Desc:
 */
@Service
@Slf4j
public class MercahntService {

    @Autowired
    private RestTemplate restTemplate;

    @Reference
    private MerchantServiceApi merchantServiceApi;

    @Value("${sms.url}")
    private String smsUrl;

    @Value("${oss.qiniu.accessKey}")
    private String AK;

    @Value("${oss.qiniu.secretKey}")
    private String SK;

    @Value("${oss.qiniu.bucket}")
    private String BUCKET;

    @Value("${oss.qiniu.domain}")
    private String domain;


    //商户注册
    public MerchantRegisterVo registerMerchant(MerchantRegisterVo merchantRegisterVo) throws BusinessException{

        // 1.校验
        if (merchantRegisterVo == null) {
            BusinessCast.cast(CommonErrorCode.E_100108);
        }

        //手机号非空校验
        if (StringUtils.isBlank(merchantRegisterVo.getMobile())) {
            BusinessCast.cast(CommonErrorCode.E_100112);
        }

        //校验手机号的合法性
        if (!PhoneUtil.isMatches(merchantRegisterVo.getMobile())) {
            BusinessCast.cast(CommonErrorCode.E_100109);
        }

        //联系人非空校验
        if (StringUtils.isBlank(merchantRegisterVo.getUsername())) {
            BusinessCast.cast(CommonErrorCode.E_100110);
        }
        //密码非空校验
        if (StringUtils.isBlank(merchantRegisterVo.getPassword())) {
            BusinessCast.cast(CommonErrorCode.E_100111);
        }
        //验证码非空校验
        if (StringUtils.isBlank(merchantRegisterVo.getVerifiyCode()) ||
                StringUtils.isBlank(merchantRegisterVo.getVerifiykey())) {
            BusinessCast.cast(CommonErrorCode.E_100103);
        }

        //远程调用sailing服务校验
        this.checkSmsCode(merchantRegisterVo);

        //远程调用商户服务添加商户信息
        // MerchantDTO merchantDTO = MerchantRegisterConvert.INSTANCE.vo2dto(merchantRegisterVo);
        MerchantDTO merchantDTO = new MerchantDTO();
        BeanUtils.copyProperties(merchantRegisterVo,merchantDTO);
        MerchantDTO merchantDTO1 = merchantServiceApi.registerMerchant(merchantDTO);

        //添加成功返回结果
        merchantRegisterVo=MerchantRegisterConvert.INSTANCE.dto2vo(merchantDTO1);
        return merchantRegisterVo;
    }

    //远程调用sailing服务校验
    private void checkSmsCode(MerchantRegisterVo merchantRegisterVo) throws BusinessException {
        String url = smsUrl+"/verify?name=sms&verificationCode="+merchantRegisterVo.getVerifiyCode()+"&verificationKey="+merchantRegisterVo.getVerifiykey();

        try {
            ResponseEntity<Map> forEntity = restTemplate.exchange(url, HttpMethod.POST, null, Map.class);

            if(forEntity==null){
                log.error("校验验证码出错");
                BusinessCast.cast(CommonErrorCode.E_100102);
            }
            Map responseMap = forEntity.getBody();
            if(responseMap==null || responseMap.get("result")==null || !(boolean)responseMap.get("result")){
                log.error("校验验证码出错");
                BusinessCast.cast(CommonErrorCode.E_100102);
            }

        }catch (RestClientException e){
            log.error("校验验证码出错：{}"+e.getMessage());
            e.printStackTrace();
            BusinessCast.cast(CommonErrorCode.E_100102);

        }

    }


    //文件上传
    public String upload(MultipartFile file) {
       //参数校验
        if (file == null){
            BusinessCast.cast(CommonErrorCode.E_100101);
        }
        String key = UUID.randomUUID().toString();

        //文件原始名称
        String originalFilename = file.getOriginalFilename();
        key= key+originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println("-------------------------------"+key);
        try {
            byte[] bytes = file.getBytes();
            QiniuUtils.upload2qiniu(AK,SK,BUCKET,bytes,key);
            return domain+key;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("商户注册上传证件异常：{}"+e.getMessage());
            BusinessCast.cast(CommonErrorCode.CUSTOM);
            return null;
        }

    }




    //根据ID查询商户信息
    public MerchantDTO queryMerchantById(Long merchantId) {
        MerchantDTO merchantDTO = merchantServiceApi.queryMerchantById(merchantId);
        return merchantDTO;
    }
}
